const initTitle = 'Untitled.md'

export const flattenArr = (arr) => {
    return arr.reduce((map, item) => {
        map[item.id] = item
        return map
    }, {})
}

export const objToArr = (obj) => {
    return Object.keys(obj).map(key => obj[key])
}

// 判断文件名是否重复
export const judgeFileName = (filesArr, title) => {
    let isExist = false
    filesArr.find((file) => {
        if (file.title === title) {
            isExist = true
            return file
        }
    })

    return isExist;
}

export const createDefaultTitle = (filesArr, num = 0) => {
    const title = num ? initTitle.replace('.', `${num}.`) : initTitle
    const res = judgeFileName(filesArr, title)
    if (res) {
        return createDefaultTitle(filesArr, num + 1)
    } else {
        return title
    }
}

export const getParentNode = (node, parentClassName) => {
    let current = node;
    while (current) {
        if (current.classList.contains(parentClassName)) {
            return current
        }
        current = current.parentNode
    }
    return false
}

export const timestampToString = (timestamp) => {
    const data = new Date(timestamp)
    return data.toLocaleDateString() + ' ' + data.toLocaleTimeString()
}